package com.xuanheng.utils.http.async;

import java.io.IOException;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.util.List;
import java.util.Map;


public class AsyncHttpRequest extends
        AsyncTask<Void, Integer, AsyncHttpResponse> {

    private HttpMethod method;
    private String url;
    private RequestParams params;
    private String userAgent;
    private Map<String, List<Object>> headers;
    private IResponseHandler handler;
    private HttpRequest req;

    public AsyncHttpRequest(HttpMethod method, String url,
                            RequestParams params, String userAgent,
                            Map<String, List<Object>> headers, IResponseHandler handler) {
        this.method = method;
        this.url = url;
        this.params = params;
        this.userAgent = userAgent;
        this.headers = headers;
        this.handler = handler;
        if (method == HttpMethod.POST) {
            req = new HttpPostRequest(url);
        } else if (method == HttpMethod.GET) {
            req = new HttpGetRequest(url);
        }


    }

    private void setData(HttpRequest request, AsyncHttpResponse response)
            throws MalformedURLException, IOException, SocketTimeoutException {
        request.setParameters(params);
        request.setUserAgent(userAgent);
        request.setHeaders(headers);
        int code = request.getResponseCode();
        response.setStatusCode(code);
        response.setHeaders(request.getConnection().getHeaderFields());
        if (code >= 300) {
            response.setThrowable(new Throwable(code + ""));
        }
        String str = request.getResponseBody();
        response.setResponse(str);
    }

    public void setTimeout(int timeout) {
        req.setConnectTimeout(timeout);
    }

    public void setCan302(boolean can302){
        req.setCan302(can302);
    }
    @Override
    protected AsyncHttpResponse doInBackground(Void... v) {
        // TODO Auto-generated method stub
        AsyncHttpResponse response = new AsyncHttpResponse();
        try {
            setData(req, response);
        } catch (MalformedURLException e) {
            response.setThrowable(e);
        } catch (SocketTimeoutException e) {
            response.setThrowable(e);
        } catch (ConnectException e) {
            response.setThrowable(e);
        } catch (IOException e) {
            response.setThrowable(e);
        } finally {
            req.close();
        }
        return response;
    }

    @Override
    protected void onCancelled() {
        // TODO Auto-generated method stub
        super.onCancelled();
        if (handler != null) {
            handler.onCancelled();
            handler.onFinished();
        }
    }

    @Override
    protected void onPostExecute(AsyncHttpResponse result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        if (handler != null) {
            if (result.getThrowable() != null) {
                if (result.getThrowable() instanceof SocketTimeoutException || result.getThrowable() instanceof ConnectException) {
                    handler.onTimeout();
                } else {
                    if (result != null) {
                        if (result.getStatusCode() != null) {
                            handler.onFailure(result.getStatusCode(), result.getHeaders(),
                                    result.getResponse(), result.getThrowable());
                        } else {
                            handler.onFailure(-1, result.getHeaders(),
                                    result.getResponse(), result.getThrowable());
                        }
                    }
                }
            } else {
                handler.onSuccess(result.getStatusCode(), result.getHeaders(),
                        result.getResponse());
            }
            handler.onFinished();
        }
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        if (handler != null) {
            handler.onStart();
        }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
        if (handler != null) {
            // handler.onProgress(0, 0);
        }
    }
}
